<template>
    <div>
        <div class="headerSty1" style="margin: 20px 0 10px;">
            <div class="headerLeftSty">
                <div class="textSty">方案确认</div>
            </div>
            <div>
                <el-form label-width="120px" :model="form" :rules="rules" ref="form">
                    <el-row v-for="(item, index) in constructionInfoList" :key="item.id">
                        <el-col :span="18">
                            <el-form-item label-width="40px">
                                <div class="headerLeftSty">
                                    <div class="navSty"></div>
                                    <div class="textSty1" style="margin-left: 10px;">建筑信息{{ index + 1 }}</div>
                                </div>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="建筑物">
                                {{ item.name }}
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="项目使用性质">
                                {{ item.natureOfUse }}
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="建筑高度">
                                {{ item.height }}
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="项目建筑面积">
                                {{ item.area }}
                            </el-form-item>
                        </el-col>

                    </el-row>
                    <el-row>
                        <el-col :span="6">
                            <el-form-item label="方案模板选择">
                                <el-radio-group @input="listAcc" v-model="radio">
                                    <el-radio label="1">平台</el-radio>
                                    <el-radio label="2">机构</el-radio>
                                </el-radio-group>
                                <!-- <el-select v-model="form.programmeTemplateId" placeholder="请选择"
                                    :style='{ "width": "40%" }'>
                                    <el-option v-for="(item, index) in relModelOptions" :key="index" :label="item.name"
                                        :value="item.id"></el-option>
                                </el-select> -->
                            </el-form-item>

                        </el-col>
                        <el-col :span="18">
                            <el-form-item label="" prop="programmeTemplateId" label-width="5px">
                                <el-select v-model="form.programmeTemplateId" placeholder="请选择"
                                    :style='{ "width": "40%" }'>
                                    <el-option v-for="(item, index) in relModelOptions" :key="index" :label="item.name"
                                        :value="item.id"></el-option>
                                </el-select>
                            </el-form-item>

                        </el-col>
                        <el-col :span="24" v-if="dataForm.status == 6">
                            <el-form-item label-width="40px">
                                <el-button type="primary" @click="generateContract" :loading="scLoad">生成方案</el-button>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row v-if="noneProject">
                        <!-- 方案预览 -->
                        <el-col :span="24">
                            <el-form-item label-width="40px">
                                <div class="headerSty" style="width: 100%;">
                                    <div class="headerLeftSty">
                                        <div class="navSty"></div>
                                        <div class="textSty1" style="margin-left: 10px;color: rgb(90, 156, 248);">方案预览
                                        </div>
                                    </div>
                                    <div>
                                        <el-button type="primary" v-if="btnState" @click="updateState">编辑方案</el-button>
                                        <el-button type="primary" v-else @click="recoverContract">复原</el-button>
                                        <el-button type="primary" v-if="!btnState" @click="updateContract"
                                            :loading="updateBtnLoading">保存</el-button>
                                    </div>

                                </div>
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label-width="40px" v-if="btnState">
                                <div class="rickSty">
                                    <div v-html="textRich">
                                    </div>
                                </div>
                            </el-form-item>
                            <el-form-item label-width="40px" v-else>
                                <EditorPlus :min-height="512" v-model="textRich" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label-width="120px" label="文档附件" style="font-weight: normal;">
                                <el-upload class="upload-demo" :limit="10" :action="uploadUrl"
                                    :before-remove="beforeRemove" :file-list="fileList" :on-success="handleFileSuccess"
                                    :before-upload="beforeAvatarUpload">
                                    <el-button size="small" type="primary">点击上传</el-button>
                                    <div slot="tip" class="el-upload__tip">
                                        支持格式：.rar .zip .doc .docx .pdf ，单个文件不能超过20MB
                                    </div>
                                </el-upload>
                            </el-form-item>
                        </el-col>

                    </el-row>
                    <el-row>
                        <el-col :span="24">
                            <el-form-item label-width="40px">
                                <el-button type="primary" @click="toRouter">查看计划</el-button>
                                <el-button type="danger" @click="downloadContract">方案下载</el-button>
                                <el-button type="primary" @click="submitContract"
                                    v-if="dataForm.status == 6 && noneProject">提交</el-button>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
        </div>
    </div>
</template>
<script>
import {
    getContractBuildingInfo, getUpAnnex, saveUpAnnex, getTemplateList, getTemplatePublicList,
    generateMaintenancePlan, createContract, dowRichText, putContract, getCustomerDetail, getTemplateListTpe
} from "@/api/contract/contractOrg";
import { tansParams, blobValidate } from "@/utils/ruoyi";
import { saveAs } from 'file-saver'
export default {
    props: {
        dataForm: {
            type: Object,
            default: {},
        }
    },
    data() {
        return {
            form: {},
            // 表单校验
            rules: {
                programmeTemplateId: [
                    {
                        required: true,
                        message: '请选择',
                        trigger: "change"
                    }
                ]
            },
            tableData: [],
            // 建筑信息
            constructionInfoList: [],
            relModelOptions: [],
            radio: '1',
            btnState: true,
            // 富文本
            textRich: '',
            uploadUrl: process.env.VUE_APP_BASE_API + "/common/upload",
            uploadList: [],
            fileList: [],
            noneProject: false,
            scLoad: false,
            btnStateList: true,
            updateBtnLoading: false
        }
    },
    created() {
        this.form.programmeTemplateId = undefined
        if (Object.keys(this.dataForm).length !== 0 && this.dataForm.id !== 0) {
            this.form = { ...this.form, ...this.dataForm }
            if (this.dataForm.programmeRichText) {
                this.textRich = this.dataForm.programmeRichText
                this.noneProject = true
                this.btnStateList = true
            }
            if (this.dataForm.programmeTemplateId) {
                this.getTemplateIdList()
            }
            this.getList()
        }

    },
    methods: {
        getList() {
            getContractBuildingInfo(this.dataForm.contractId).then(res => {
                this.constructionInfoList = res.data
            })
            // 获取模板列表
            getTemplatePublicList('PROGRAMME').then(res => {
                this.relModelOptions = res.data
            })
            // 合同附件
            getUpAnnex(this.dataForm.id, '4').then(res => {
                for (let i = 0; i < res.data.length; i++) {
                    this.fileList.push({
                        name: res.data[i].fileName,
                        url: res.data.filePath
                    })
                }
            })
        },
        getTemplateIdList() {
            // 模板列表 isCommon true 平台
            getTemplateListTpe().then(res => {
                for (let i = 0; i < res.data.length; i++) {
                    if (res.data[i].id == this.dataForm.templateId) {
                        if (res.data[i].isCommon == true) {
                            this.radio = '1'
                        } else {
                            this.radio = '2'
                        }
                    }

                }
            })
        },
        // 模板切换
        listAcc(row) {
            this.form.programmeTemplateId = undefined
            if (row == 2) {
                getTemplateList('PROGRAMME').then(res => {
                    this.relModelOptions = res.data
                })
            } else {
                getTemplatePublicList('PROGRAMME').then(res => {
                    this.relModelOptions = res.data
                })
            }
        },
        updateState() {
            this.btnState = !this.btnState
        },
        // 生成方案
        generateContract() {
            this.$refs['form'].validate((valid) => {
                if (valid) {
                    let data = Object.assign({}, this.form)
                    if (data.projectSaveDTO.engineer) {
                        if (Array.isArray(data.projectSaveDTO.engineer)) {
                            data.projectSaveDTO.engineer = data.projectSaveDTO.engineer.join(',')
                        } else {
                            data.projectSaveDTO.engineer = data.projectSaveDTO.engineer
                        }
                    } else {
                        data.projectSaveDTO.engineer = ''
                    }
                    if (data.projectSaveDTO.operators) {
                        if (Array.isArray(data.projectSaveDTO.operators)) {
                            data.projectSaveDTO.operators = data.projectSaveDTO.operators.join(',')
                        } else {
                            data.projectSaveDTO.operators = data.projectSaveDTO.operators
                        }
                    } else {
                        data.projectSaveDTO.operators = ''
                    }
                    this.scLoad = true
                    createContract(data).then(res => {
                        generateMaintenancePlan(this.dataForm.contractId).then(list => {
                            this.textRich = list.msg
                            this.noneProject = true
                        }).finally(() => {
                            this.scLoad = false
                        })
                    })
                }
            })

        },
        // 跳转
        toRouter() {
            this.$router.push('/plan-produce/task-index?customerId=' + this.form.customerId)
        },
        // 下载方案
        downloadContract() {
            dowRichText({
                fileName: this.form.name + '维保方案',
                data: this.textRich
            }).then(async (data) => {
                const isBlob = blobValidate(data.data);
                const filename = decodeURIComponent(data.filename);
                if (isBlob) {
                    saveAs(data.data, filename)
                } else {
                    const resText = await data.text();
                    const rspObj = JSON.parse(resText);
                    const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']
                    this.$modal.msgError(errMsg);
                }
            })
        },
        // 复原
        recoverContract() {
            let data = Object.assign({}, this.form)
            if (data.projectSaveDTO.engineer) {
                if (Array.isArray(data.projectSaveDTO.engineer)) {
                    data.projectSaveDTO.engineer = data.projectSaveDTO.engineer.join(',')
                } else {
                    data.projectSaveDTO.engineer = data.projectSaveDTO.engineer
                }
            } else {
                data.projectSaveDTO.engineer = ''
            }
            if (data.projectSaveDTO.operators) {
                if (Array.isArray(data.projectSaveDTO.operators)) {
                    data.projectSaveDTO.operators = data.projectSaveDTO.operators.join(',')
                } else {
                    data.projectSaveDTO.operators = data.projectSaveDTO.operators
                }
            } else {
                data.projectSaveDTO.operators = ''
            }
            createContract(data).then(res => {
                generateMaintenancePlan(this.dataForm.contractId).then(list => {
                    this.textRich = list.msg
                    this.btnState = !this.btnState
                })
            })
        },
        updateContract() {
            // this.$emit('loadingState')
            this.updateBtnLoading = true
            putContract({
                programmeRichText: this.textRich,
                id: this.form.contractId
            }).then(res => {
                getCustomerDetail(this.form.contractId).then(list => {
                    this.updateBtnLoading = false
                    this.textRich = list.data.programmeRichText
                    this.btnState = !this.btnState
                });
            })
        },

        // 提交
        submitContract() {
            this.form.status = this.form.status > 6 ? this.form.status : 7
            // 保存附件
            if (this.uploadList.length) {
                let annexList = []
                for (let i = 0; i < this.uploadList.length; i++) {
                    if (this.uploadList[i].response) {
                        annexList.push({
                            fileName: this.uploadList[i].name,
                            filePath: this.uploadList[i].response.fileName,
                            type: 4
                        })
                    } else {
                        annexList.push({
                            fileName: this.uploadList[i].name,
                            filePath: this.uploadList[i].url,
                            type: 4
                        })
                    }
                }
                saveUpAnnex({ contractId: this.form.id, annexList }).then(res => {
                })
            }
            putContract({
                programmeRichText: this.textRich,
                id: this.form.contractId
            }).then(res => {
                this.$emit('refreshConfirmation', { ...this.form, programmeRichText: this.textRich })
            })



        },

        // 移除上传
        beforeRemove(file, fileList) {
            this.uploadList = fileList

        },
        // 文件上传成功处理
        handleFileSuccess(response, file, fileList) {
            this.uploadList = fileList
        },
        // 文件上传前的大小
        beforeAvatarUpload(file) {
            const isRAR = file.type === 'application/x-rar-compressed';
            const isZIP = file.type === 'application/zip';
            const isMSOffice = file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' || // .docx  
                file.type === 'application/vnd.ms-word' || // .doc  
                file.type === 'application/pdf'; // .pdf  

            const isAccepted = isRAR || isZIP || isMSOffice;
            const isLt2M = file.size / 1024 / 1024 < 20;
            if (!isAccepted) {
                this.$message.error('上传文件格式不正确，请上传 .rar、.zip、.doc、.docx 或 .pdf 格式的文件！');
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 20MB!');
            }
            return isAccepted && isLt2M;
        },
    }
}
</script>

<style lang="scss" scoped>
.headerSty {
    display: flex;
    justify-content: space-between;
    width: 97%;

    .headerLeftSty {
        display: flex;
        align-items: center;

        .textSty {
            margin-left: 8px;
            font-size: 16px;
            font-weight: 700;
        }
    }
}

.rickSty {
    border: 1px solid #999;
    height: 512px;
    overflow-y: auto;
}


.headerSty1 {
    width: 97%;

    .headerLeftSty {
        display: flex;
        align-items: center;

        .textSty1 {
            margin-left: 8px;
            font-size: 14px;
            font-weight: 700;
        }

        .textSty {
            margin-left: 8px;
            font-size: 16px;
            font-weight: 600;
        }
    }
}

.navSty {
    height: 15px;
    width: 5px;
    background: rgb(90, 156, 248);
}


.contSty {
    display: flex;

    .contLeftSty {
        height: 80px;
        width: 5px;
        background: rgb(90, 156, 248);
    }

    .allBlo {
        margin-left: 5px;
    }

    .LastBlockSty {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 132px;
        height: 30px;
        background: white;
        border-radius: 5px;
        color: rgb(90, 156, 248);
        border: 1px solid rgb(90, 156, 248);

        .el-icon-warning {
            color: rgb(90, 156, 248);
            font-weight: bolder;
            margin-right: 5px;
            font-size: 18px;
        }
    }

    .blockSty {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 132px;
        height: 30px;
        background: rgb(90, 156, 248);
        border-radius: 5px;
        color: white;

        .el-icon-check {
            color: white;
            font-weight: bolder;
            margin-right: 5px;
            font-size: 18px;
        }

        .el-icon-close {
            color: white;
            font-weight: bolder;
            margin-right: 5px;
            font-size: 18px;
        }
    }

    .lastTeSty {
        flex: 1;
        height: 120px;
        background: white;
        margin-left: 10px;
        border-radius: 5px;
        border: 1px solid rgb(90, 156, 248);
        overflow-y: auto;
    }
}

.text1 {
    font-size: 14px;
    font-weight: 500;
}

.text2 {
    font-size: 14px;
    color: #999;
}

.el-icon-arrow-right {
    color: rgb(90, 156, 248);
    font-weight: bolder;
    margin: 0 10px;
    font-size: 32px;
}
</style>